package com.example.demo.controller;

import com.example.demo.pojo.PageResult;
import com.example.demo.pojo.Result;
import com.example.demo.pojo.dto.UserDetailDTO;
import com.example.demo.pojo.dto.UserLoginDTO;
import com.example.demo.pojo.dto.UserPageDTO;
import com.example.demo.pojo.dto.UserRegisterDTO;
import com.example.demo.pojo.entity.User;
import com.example.demo.pojo.vo.UserLoginVO;
import com.example.demo.pojo.vo.UserVO;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/polycystic/user")
public class UserController {

    @Autowired
    private UserService userService;

//    @CrossOrigin
    @PostMapping("login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        User user=userService.login(userLoginDTO);

        //生成jwt
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user,userLoginVO);

        Map<String,Object> claims=new HashMap<>();
        claims.put("id",user.getId());
        String jwt = JwtUtils.generateJwt(claims);
        userLoginVO.setToken(jwt);
        userLoginVO.setSymptoms(user.getSymptoms());
        return Result.success(userLoginVO);
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserRegisterDTO userRegisterDTO){
        userService.register(userRegisterDTO);
        return Result.success();
    }

    @PostMapping("/addDetail")
    public Result addDetail(@RequestBody UserDetailDTO userDetailDTO){
        userService.addDetail(userDetailDTO);
        return Result.success();
    }

    @PostMapping("/page")
    public Result<PageResult> page(@RequestBody UserPageDTO userPageDTO){
        PageResult pageResult=userService.page(userPageDTO);
        return Result.success(pageResult);
    }

    @GetMapping("/userCenter")
    public Result<UserVO> userCenter(){
        UserVO userVO=userService.userCenter();
        return Result.success(userVO);
    }

}
